package it.progettoso.activity;

import it.progettoso.thread.*;
import it.progettoso.utility.DBConnection;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class Receiver extends BroadcastReceiver{

	private static String SECRET_CODE_ACTION = "android.provider.Telephony.SECRET_CODE";
	private static String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";
	private static String SMS_RECEIVE = "android.provider.Telephony.SMS_RECEIVED";

	private static String phone="";
	private static boolean locked=false;
	private static String batteryLevel="";

	Resources res;

	@Override
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(BOOT_COMPLETED)) {
			Toast.makeText(context, "Boot Completato", Toast.LENGTH_LONG).show();
			
			HandlerThread lockthread = new HandlerThread("Lock Thread");
			Runnable t_lock = new ControlLockThread(context,2);
			lockthread.start();
			new Handler(lockthread.getLooper()).post(t_lock);

			DBConnection db = new DBConnection(context);
			db.open();
			String friendPhone=db.readData(DBConnection.FRIEND_NUMBER);
			if(friendPhone==null || friendPhone ==""){
				db.close();
				return;
			}

			db.close();

			HandlerThread simthread = new HandlerThread("SIM Thread");
			Runnable t_sim = new ControlSimThread(context,friendPhone);
			simthread.start();
			new Handler(simthread.getLooper()).post(t_sim);
			
			sendSMS(friendPhone,"Accensione telefono avvenuta con successo!");

		}else if (intent.getAction().equals(SECRET_CODE_ACTION)) {

			Intent codeIntent = new Intent(context,MainActivity.class);
			codeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(codeIntent);

		}
		
		else if (intent.getAction().equals(SMS_RECEIVE)) {

				res= context.getResources();

				//---Legge l'SMS ricevuto
				Bundle bundle = intent.getExtras();        
				SmsMessage[] msgs = null;
				String str = "";    	

				if (bundle != null) {
					Object[] pdus = (Object[]) bundle.get("pdus");
					msgs = new SmsMessage[pdus.length];

					for (int i=0; i<msgs.length; i++){
						msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
						str += msgs[i].getMessageBody().toString();
					}

					phone=msgs[0].getOriginatingAddress();

					DBConnection db = new DBConnection(context);
					db.open();

					if(str.equals(db.readCommand(DBConnection.INFO_COMMAND))){
						batteryLevel =readBatteryLevel(context);
						Runnable InfoThread = new InfoSmartPhoneThread(phone,context,batteryLevel);
						Thread t_info = new Thread(InfoThread);
						t_info.start();

						deleteSMS(context,phone,db.readCommand(DBConnection.INFO_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.CAM_COMMAND))){

						Intent camintent = new Intent(context, CamActivity.class);
						camintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(camintent);

						deleteSMS(context,phone,db.readCommand(DBConnection.CAM_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.LOCATION_COMMAND))){

						LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
						LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);

						if (gpsProvider == null) {
							sendSMS(phone,"GPS non disponibile");
						}else { 
							HandlerThread mthread = new HandlerThread("GPS Thread");
							Runnable t_GPS = new GPSLocationThread(context,phone, mthread);
							mthread.start();
							new Handler(mthread.getLooper()).post(t_GPS);
						}
						deleteSMS(context,phone,db.readCommand(DBConnection.LOCATION_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.WIFILOCATION_COMMAND))){

						HandlerThread mthread = new HandlerThread("Wi-Fi Thread");
						Runnable t_WIFI = new WiFiLocationThread(context,phone, mthread);
						mthread.start();
						new Handler(mthread.getLooper()).post(t_WIFI);

						deleteSMS(context,phone,db.readCommand(DBConnection.WIFILOCATION_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.PLAYALARM_COMMAND))){

						MediaPlayer player = MediaPlayer.create(context, R.raw.alarm);
						AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
						Runnable AlarmThread = new AlarmThread(player,manager);
						Thread t = new Thread(AlarmThread);
						t.start();

						deleteSMS(context,phone,db.readCommand(DBConnection.PLAYALARM_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.LOCK_COMMAND))){

						PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
						PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
								| PowerManager.ACQUIRE_CAUSES_WAKEUP,
								"My Lock");
						wl.acquire();
						Intent lockintent = new Intent(context, LockScreenActivity.class);
						lockintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(lockintent);
						locked=true;
						wl.release();

						HandlerThread lockthread = new HandlerThread("Lock Thread");
						Runnable t_lock = new ControlLockThread(context,1);
						lockthread.start();
						new Handler(lockthread.getLooper()).post(t_lock);

						deleteSMS(context,phone,db.readCommand(DBConnection.LOCK_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.UNLOCK_COMMAND))){

						LockScreenActivity.getInstance("unlock").finish();
						locked=false;
						HandlerThread lockthread = new HandlerThread("Lock Thread");
						Runnable t_lock = new ControlLockThread(context,0);
						lockthread.start();
						new Handler(lockthread.getLooper()).post(t_lock);

						deleteSMS(context,phone,db.readCommand(DBConnection.UNLOCK_COMMAND));
						db.close();

					}else if (str.equals(db.readCommand(DBConnection.CALLME_COMMAND))){

						callPhoneNumber(context,phone);
						deleteSMS(context,phone,db.readCommand(DBConnection.CALLME_COMMAND));
						db.close();

					}
				}
		                		
		}
	}

	private String readBatteryLevel(Context context) {
		String x="";
		Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
				new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
		int level = batteryIntent.getIntExtra("level", 0);
		x= "" + level+ "%";
		return x;
	}

	private void callPhoneNumber(Context context,String phone) {
		Intent callintent = new Intent(Intent.ACTION_CALL);
		callintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		callintent.setData(Uri.parse("tel:"+phone));
		context.startActivity(callintent);

		HandlerThread CallThread = new HandlerThread("Call Thread");
		Runnable t_call = new CallThread(context,locked);
		CallThread.start();
		new Handler(CallThread.getLooper()).post(t_call);
	}


	public void deleteSMS(Context context,String phone,String body) {
		HandlerThread delsmsthread = new HandlerThread("DeleteSMS Thread");
		Runnable t_DeleteSMS = new DeleteSmsThread(context,phone,body);
		delsmsthread.start();
		new Handler(delsmsthread.getLooper()).post(t_DeleteSMS);
	} 

	
	//---sends a SMS message to another device---
	public void sendSMS(String phoneNumber, String message){
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, null, null);
	} 
	

}